#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;

#include "log.hpp"

#define FIFO_FILE "./myfifo"
#define MODE 0664


enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};


Log log;
const int size = 4096;
const string pathname = "/home/ykh";
const int proj = 0x954;


int GetKey()
{
    key_t k = ftok(pathname.c_str(), proj);
    if(k < 0)
    {
        log(Fatal, "ftok error: %s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success, key is 0x%x", k);
    return k;
}


int GetShareMem(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k, size, flag);
    if(shmid < 0)
    {
        log(Fatal, "create share memory error: %s", strerror(errno));
        exit(2);
    }
    log(Info, "create share memory success, shmid: %d", shmid);
    return shmid;
}


int CreateShm()
{
    return GetShareMem(IPC_CREAT | IPC_EXCL | 0666);
}


int GetShm()
{
    return GetShareMem(IPC_CREAT);
}


class Init
{
public:
    Init()
    {
        int c = mkfifo(FIFO_FILE, MODE);
        if(c == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }

    ~Init()
    {
        int d = unlink(FIFO_FILE);
        if(d == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};